package com.sheep.opt;

import org.apache.log4j.PropertyConfigurator;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: wnj
 * Date: 2010-11-2
 * Time: 19:20:25
 * To change this template use File | Settings | File Templates.
 */
public class DbConnector {
    private static DataSource _pool_wnj;

    // 使用数据源连接
    public static Connection getConn_ds() {
        String DS_WNJ = "jdbc/write";
        try {
            if(_pool_wnj == null){
                Context env = (Context) new InitialContext().lookup("java:comp/env");
                _pool_wnj = (DataSource) env.lookup(DS_WNJ);
            }
            return _pool_wnj.getConnection();
        } catch (Exception e) {
            System.out.println("DS方式数据库连接异常: " + e.getMessage());
            return null;
        }
    }

    // 使用配置文件的池连接数据库
    public static Connection getConn_pool() {
        String configFile = "/datasource.properties";
        String configPool = "proxool.test";
        try {
            Properties dbProps = new Properties();
            dbProps.load(DbConnector.class.getResourceAsStream(configFile));
            PropertyConfigurator.configure(dbProps);
            return DriverManager.getConnection(configPool);
        } catch (Exception e) {
            System.out.println("POOL方式数据库连接异常: " + e.getMessage());
            return null;
        }
    }    

    //使用JDBC连接数据库
    public static Connection getConn_jdbc() {
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "root";
        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection(url, username, password);
            return conn;
        }catch (Exception e){
            System.out.println("JDBC方式数据库连接异常: " + e.getMessage());
            return null;
        }
    }

    //多方法连接
    public static Connection getConn(){
        Connection conn = getConn_ds();
        if(conn == null){
            conn = getConn_pool();
            if(conn == null){
                conn = getConn_jdbc();
            }
            }
            return conn;
        }
    }


//            InitialContext ctx = new InitialContext();
//            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/broker");
//            Connection conn = ds.getConnection();
